package helper;

import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

public class JsonHelper
{
    private static Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
    private static JsonParser parser = new JsonParser();

    @SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> T convertFromJsonToObject(final String jsonString, final Class type)
    {
        return (T) prettyGson.fromJson(jsonString, type);
    }

    @SuppressWarnings("rawtypes")
	public static <T> T convertFromJsonToObjectList(final String jsonString, final Class type)
    {
    	Type classType = TypeToken.getParameterized(List.class, type).getType();
    	return prettyGson.fromJson(jsonString, classType);
    }

    public static String convertFromObjecttoJson(final Object o)
    {
        return prettyGson.toJson(o);
    }

    public static JsonObject convertFromStringToJson(String s){
        return parser.parse(s).getAsJsonObject();
    }
    
    /**
     * 格式化 json字符串
     * @param str 待格式化的字符串
     * */
    public static String GetJsonString(String str) {
		Gson gson = new GsonBuilder()
				.setPrettyPrinting()
				.serializeNulls() // 在序列化时不忽略 null
				.create();
		return gson.toJson(JsonParser.parseString(str));
	}
}
